<template>
  <div ref="preview-container" class="preview-container pb-40">
    <div class="w-[800px] mx-auto">
      <div
        class="w-full h-16 px-5 top-0 left-0 bg-transparent z-50 flex space-between items-center"
      >
        <div class="flex space-between no-print">
          <el-button type="danger" @click="gobackHandle">返回</el-button>
          <el-button type="success" @click="genQuiz">生成在线问卷</el-button>
          <el-button type="warning" @click="genPDF">生成本地PDF</el-button>
        </div>
      </div>
      <div
        class="p-5 border border-gray-200 rounded-md bg-white shadow-md no-border"
      >
        <div class="mb-2" v-for="(com, index) in editorStore.coms" :key="index">
          <component
            :is="com.type"
            :status="com.status"
            :serialNum="index + 1"
          />
        </div>
      </div>
    </div>
  </div>
  <!-- <el-dialog v-model="dialogVisible" title="信息" width="500">
    分享链接:
    <a :href="quizLink" target="_blank">{{ quizLink }}</a>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="copyLink">复制链接</el-button>
      </div>
    </template>
  </el-dialog> -->
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import surveyDBOperation from "@/db/operation";
import { restoreComJsonSchema } from "@/utils/dbUtils";
import { useEditorStore } from "@/stores/useEditor";
import { getUnAllowPrintComs } from "@/utils/printUtils";

const router = useRouter();
const route = useRoute();

// - 当前问卷的id
const id = Number(route.params.id);

const editorStore = useEditorStore();

const getSurvey = () => {
  if (id) {
    surveyDBOperation.getSurveyById(id).then((res) => {
      console.log(res);
      restoreComJsonSchema(res!.coms);

      editorStore.setComs(res!.coms);
    });
  }
};
getSurvey();

// * 返回按钮
const gobackHandle = () => {
  // router.back();
  const { from } = history.state;
  if (from === "home") {
    router.back();
  } else {
    router.push(`/editor/${id}/survey-types`);
  }
};

// * 生成在线问卷
const genQuiz = () => {
  console.log("生成在线问卷");
};

// * 生成本地PDF
const genPDF = () => {
  const unAllowPrintComs = getUnAllowPrintComs(editorStore.coms);
  console.log(unAllowPrintComs);
  if (unAllowPrintComs.length > 0) {
    ElMessage.error(
      `当前问卷包含不可打印的组件(${unAllowPrintComs
        .map((i) => i.comName)
        .join(",")})，不能生成PDF`,
    );
    return unAllowPrintComs;
  } else {
    window.print();
  }
};

defineOptions({
  meta: {
    title: "问卷预览",
    __isRouteComponent: true,
    __props: {
      id: {
        reg: "(\\d+)?",
      },
    },
  },
});
</script>

<style scoped lang="scss">
.preview-container {
  width: 100vw;
  min-height: 100vh;
  background: url("@/assets/imgs/editor_background.png");
}

@media print {
  .no-print {
    display: none;
  }
  .no-border {
    border: none;
    box-shadow: none;
  }
}
</style>
